package cn.kt.springbootuploadmaster.service.impl;

import cn.kt.springbootuploadmaster.repository.FileChunkMapper;
import cn.kt.springbootuploadmaster.service.FileChunkService;
import cn.kt.springbootuploadmaster.service.LocalStorageService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.api.entity.upload.FileChunk;
import com.example.api.entity.upload.FileChunkParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import utils.BeanUtils;

import java.util.List;

/**
 * Created by tao.
 * Date: 2022/6/29 10:53
 * 描述:
 */
@Service
@Slf4j
@AllArgsConstructor
public class FileChunkServiceImpl extends ServiceImpl<FileChunkMapper, FileChunk> implements FileChunkService {
    private final FileChunkMapper fileChunkRepository;

    private final LocalStorageService localStorageService;

    @Override
    public List<FileChunk> findByMd5(String md5) {
        final LambdaQueryWrapper<FileChunk> eq = Wrappers.<FileChunk>lambdaQuery().eq(FileChunk::getIdentifier, md5);
        return fileChunkRepository.selectList(eq);
    }

    @Override
    public void saveFileChunk(FileChunkParam param) {
        fileChunkRepository.insert(BeanUtils.toBean(param,FileChunk.class));
        // 当文件分片完整上传完成，存一份在LocalStorage表中
        if (param.getChunkNumber().equals(param.getTotalChunk())) {
            localStorageService.saveLocalStorage(param);
        }
    }

    @Override
    public void delete(FileChunkParam fileChunk) {
        fileChunkRepository.deleteById(fileChunk.getId());
    }

    @Override
    public void deleteById(Long id) {
        fileChunkRepository.deleteById(id);
    }
}
